<template>
  <div class="login-bg-fixed">
    <div class="login-split-bg">
      <div class="login-split-inner">
        <div class="login-split-left">
          <img class="platform-logo" src="/favicon.ico" alt="法律援助平台LOGO" />
          <div class="platform-title">法律援助平台</div>
          <div class="platform-desc">为社会弱势群体提供专业、便捷的法律咨询与援助服务，守护您的合法权益。</div>
          <div class="platform-slogan">让法律温暖每一个需要帮助的人</div>
        </div>
        <div class="login-split-right">
          <div class="login-box">
            <div class="login-header">
              <span class="login-header-title">登录</span>
              <span class="login-header-link" @click="showRegister = true">没有账号？立即注册</span>
            </div>
            <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="0" class="no-resize-form">
              <el-form-item label="" prop="loginRole" class="role-select-item">
                <el-select v-model="loginForm.loginRole" placeholder="请选择角色" style="width: 50%">
                  <el-option label="普通用户" value="user" />
                  <el-option label="律师" value="lawyer" />
                </el-select>
              </el-form-item>
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入用户名/手机号/邮箱" :resize="'none'">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password :resize="'none'">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="captcha" class="captcha-row">
                <el-input v-model="loginForm.captcha" placeholder="请输入验证码" maxlength="4" style="flex:1;" :resize="'none'">
                  <template #prefix>
                    <el-icon><CircleCheck /></el-icon>
                  </template>
                </el-input>
                <img class="captcha-img" src="https://dummyimage.com/80x32/27ae60/fff&text=3m5s" alt="验证码" />
              </el-form-item>
              <div class="login-options">
                <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                <span class="login-forgot">忘记密码？</span>
              </div>
              <el-form-item>
                <el-button type="primary" @click="onLogin" :loading="loading" class="login-btn">登 录</el-button>
              </el-form-item>
            </el-form>
            <div class="login-tip">如需法律援助，请联系平台管理员获取账号</div>
            <div class="login-divider">其他方式登录</div>
            <div class="login-socials">
              <el-icon class="social-icon"><User /></el-icon>
              <el-icon class="social-icon"><Lock /></el-icon>
              <el-icon class="social-icon"><CircleCheck /></el-icon>
            </div>
          </div>
          <el-dialog v-model="showRegister" title="注册账号" width="480px" :close-on-click-modal="false">
            <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="registerForm.username" placeholder="请输入用户名（3-20个字符）" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="registerForm.email" placeholder="请输入邮箱地址" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="registerForm.phone" placeholder="请输入手机号码" />
              </el-form-item>
              <el-form-item label="真实姓名" prop="real_name">
                <el-input v-model="registerForm.real_name" placeholder="请输入真实姓名" />
              </el-form-item>
              <el-form-item label="身份证" prop="idCard">
                <el-input v-model="registerForm.idCard" placeholder="请输入身份证号码" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="registerForm.password" type="password" placeholder="请输入密码（6-20个字符）" show-password />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirm">
                <el-input v-model="registerForm.confirm" type="password" placeholder="请再次输入密码" show-password />
              </el-form-item>
              <el-form-item label="用户类型" prop="user_type">
                <el-select v-model="registerForm.user_type" placeholder="请选择用户类型" style="width: 100%">
                  <el-option label="普通用户" value="user" />
                  <el-option label="律师" value="lawyer" />
                </el-select>
              </el-form-item>
              <el-form-item label="验证码" prop="captcha">
                <el-input v-model="registerForm.captcha" placeholder="请输入验证码" maxlength="4" style="width: 140px; margin-right: 10px;" />
                <img class="captcha-img" src="https://dummyimage.com/80x32/27ae60/fff&text=3m5s" alt="验证码" />
              </el-form-item>
              <el-form-item label="头像">
                <input type="file" accept="image/*" @change="handleAvatarChange" />
                <img v-if="registerForm.avatar" :src="registerForm.avatar" alt="头像预览" style="width:40px;height:40px;border-radius:50%;margin-left:10px;" />
              </el-form-item>
              <el-form-item label="用户协议" prop="agreement">
                <el-checkbox v-model="registerForm.agreement">
                  我已阅读并同意
                  <el-link type="primary" @click="showAgreement">《用户协议》</el-link>
                  和
                  <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
                </el-checkbox>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="showRegister = false">取消</el-button>
                <el-button type="primary" @click="onRegister">注册</el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserAuthStore } from '@/stores/userAuth'
import { User, Lock, CircleCheck } from '@element-plus/icons-vue'
import { userAPI } from '@/api/index'

const userAuth = useUserAuthStore()

const loginForm = ref({
  username: '',
  password: '',
  captcha: '',
  loginRole: 'user'
})
const loading = ref(false)
const loginFormRef = ref(null)
const router = useRouter()
const rememberMe = ref(false)

const rules = {
  loginRole: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名/手机号/邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 注册相关
const showRegister = ref(false)
const registerForm = ref({
  username: '',
  email: '',
  phone: '',
  real_name: '', // 数据库字段名
  idCard: '',
  password: '',
  confirm: '',
  user_type: 'user', // 数据库字段名
  captcha: '',
  avatar: '',
  agreement: false
})
const registerFormRef = ref(null)

// 密码确认验证
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  real_name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{17}([0-9Xx])$)/, message: '身份证格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirm: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  user_type: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value.toLowerCase() !== '3m5s') {
          callback(new Error('验证码错误'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  agreement: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

function handleAvatarChange(e) {
  const file = e.target.files[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = (event) => {
    registerForm.value.avatar = event.target.result
  }
  reader.readAsDataURL(file)
}

function showAgreement() {
  ElMessage.info('用户协议内容...')
}

function showPrivacy() {
  ElMessage.info('隐私政策内容...')
}

function onRegister() {
  registerFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      // 调试：打印表单数据
      console.log('🔍 注册表单数据:', registerForm.value)
      console.log('🔍 real_name 值:', registerForm.value.real_name)
      console.log('🔍 user_type 值:', registerForm.value.user_type)
      
      // 确保必需字段有值
      if (!registerForm.value.real_name) {
        ElMessage.error('请填写真实姓名')
        return
      }
      if (!registerForm.value.user_type) {
        ElMessage.error('请选择用户类型')
        return
      }
      
      // 构建符合后端期望的数据格式
      const userData = {
        username: registerForm.value.username,
        email: registerForm.value.email,
        phone: registerForm.value.phone,
        realName: registerForm.value.real_name, // 后端期望的字段名
        idCard: registerForm.value.idCard,
        password: registerForm.value.password,
        userType: registerForm.value.user_type === 'user' ? 'PUBLIC' : 
                 registerForm.value.user_type === 'lawyer' ? 'LAWYER' : 'ADMIN', // 后端期望的值格式
        avatar: registerForm.value.avatar || '',
        status: 1, // 默认启用状态
        roleIds: [1] // 默认角色ID
      }
      
      // 调试：打印发送的数据
      console.log('🔍 发送到后端的数据:', userData)
      console.log('🔍 realName 值:', userData.realName)
      console.log('🔍 userType 值:', userData.userType)
      // 调用后端API创建用户
      const response = await userAPI.create(userData)

      console.log('🔍 响应数据:', response)

      
        ElMessage.success('注册成功！请使用新账号登录')
        showRegister.value = false
        
        // 自动填充登录表单
        loginForm.value.username = registerForm.value.username
        loginForm.value.password = registerForm.value.password
        
        // 清空注册表单
        registerForm.value.username = ''
        registerForm.value.email = ''
        registerForm.value.phone = ''
        registerForm.value.real_name = ''
        registerForm.value.idCard = ''
        registerForm.value.password = ''
        registerForm.value.confirm = ''
        registerForm.value.user_type = 'user'
        registerForm.value.captcha = ''
        registerForm.value.avatar = ''
        registerForm.value.agreement = false

    } catch (error) {
      console.error('注册失败:', error)
      ElMessage.error('注册失败：' + (error.response?.data?.message || error.message || '网络错误'))
    }
  })
}

function onLogin() {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true
    
    try {
      // 构建登录数据
      const loginData = {
        username: loginForm.value.username,
        password: loginForm.value.password
      }
      
      // 添加调试信息
      console.log('🔍 登录表单数据:', loginForm.value)
      console.log('🔍 发送到后端的数据:', loginData)
      console.log('🔍 登录URL: /api/user/login')
      
      // 调用后端API登录
      const response = await userAPI.login(loginData)
      console.log('🔍 登录响应数据:', response)
      
        // 登录成功，更新用户状态
        userAuth.login({
          token: response.token || 'mock-token',
          userInfo: {
            id: response.user.id,
            username: response.user.username,
            email: response.user.email,
            phone: response.user.phone,
            real_name: response.user.real_name,
            user_type: response.user.user_type,
            avatar: response.user.avatar || '',
            description: response.user.description || '',
            status: response.user.status || 1,
            create_time: response.user.create_time,
            update_time: response.user.update_time,
            last_login_time: new Date().toISOString(),
            role: response.user.user_type || 'user',
            permissions: response.user.permissions || ['case:manage']
          }
        })

        ElMessage.success('登录成功，欢迎进入法律援助平台！')
        router.push('/')

    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败：' + (error.response?.data?.message || error.message || '网络错误'))
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
* {
  box-sizing: border-box;
}
body, html, #app {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.bg-fixed {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  background: linear-gradient(135deg, #1abc9c 0%, #27ae60 100%);
}
.login-bg-fixed {
  position: fixed;
  inset: 0;
  width: 100vw;
  height: 100vh;
  background: #fff;
  z-index: 0;
  overflow: auto;
}
.login-split-bg {
  position: relative;
  z-index: 1;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: transparent;
}
.login-split-inner {
  display: flex;
  border-radius: 18px;
  box-shadow: 0 8px 40px 0 rgba(39,174,96,0.13);
  overflow: hidden;
  background: #fff;
  min-width: 720px;
  max-width: 980px;
  min-height: 480px;
}
.login-split-left {
  flex: 1.2;
  background: linear-gradient(135deg, #1abc9c 0%, #27ae60 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  padding: 0 40px;
  min-width: 340px;
}
.login-split-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  min-width: 340px;
}
.login-box {
  width: 380px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 40px 0 rgba(39,174,96,0.10);
  padding: 38px 32px 28px 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.platform-logo {
  width: 72px;
  height: 72px;
  border-radius: 16px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(39,174,96,0.13);
}
.platform-title {
  font-size: 32px;
  font-weight: 900;
  letter-spacing: 4px;
  margin-bottom: 18px;
  text-shadow: 0 2px 12px rgba(39,174,96,0.18);
}
.platform-desc {
  font-size: 18px;
  margin-bottom: 16px;
  text-align: center;
  line-height: 1.6;
  opacity: 0.95;
}
.platform-slogan {
  font-size: 20px;
  font-weight: bold;
  margin-top: 30px;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px rgba(39,174,96,0.18);
}
.login-header {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
}
.login-header-title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
}
.login-header-link {
  color: #27ae60;
  font-size: 15px;
  cursor: pointer;
  transition: text-decoration 0.2s;
}
.login-header-link:hover {
  text-decoration: underline;
}
.el-input {
  border-radius: 8px;
  font-size: 16px;
  height: 44px;
  resize: none !important;
}
.captcha-row {
  display: flex;
  align-items: center;
}
.captcha-img {
  margin-left: 0;
  border-radius: 6px;
  height: 32px;
  width: 80px;
  box-shadow: 0 2px 8px rgba(39,174,96,0.13);
  background: #f5f7fa;
  object-fit: cover;
}
.login-options {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #888;
}
.login-forgot {
  color: #27ae60;
  cursor: pointer;
  font-size: 14px;
}
.login-btn {
  width: 100%;
  height: 44px;
  border-radius: 22px;
  background: linear-gradient(90deg, #1abc9c 0%, #27ae60 100%);
  font-size: 20px;
  font-weight: bold;
  letter-spacing: 4px;
  box-shadow: 0 2px 8px rgba(39,174,96,0.13);
  border: none;
  margin-top: 8px;
}
.login-tip {
  color: #888;
  font-size: 14px;
  margin-top: 18px;
  text-align: center;
  letter-spacing: 1px;
}
.login-divider {
  width: 100%;
  text-align: center;
  color: #bbb;
  font-size: 14px;
  margin: 18px 0 8px 0;
  position: relative;
}
.login-divider::before, .login-divider::after {
  content: '';
  display: inline-block;
  width: 30%;
  height: 1px;
  background: #eee;
  vertical-align: middle;
  margin: 0 8px;
}
.login-socials {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 18px;
  margin-bottom: 8px;
}
.social-icon {
  font-size: 28px;
  color: #27ae60;
  cursor: pointer;
  transition: color 0.2s;
}
.social-icon:hover {
  color: #1abc9c;
}
.role-select-item {
  display: flex;
  justify-content: center;
  margin-bottom: 18px;
}
.role-select-item .el-select {
  border-radius: 8px;
  font-size: 16px;
  height: 44px;
}
@media (max-width: 900px) {
  .login-split-bg {
    align-items: flex-start;
    justify-content: flex-start;
  }
  .login-split-inner {
    flex-direction: column;
    min-width: 95vw;
    max-width: 100vw;
    min-height: 0;
    box-shadow: none;
    border-radius: 0;
  }
  .login-split-left, .login-split-right {
    min-width: 100vw;
    width: 100vw;
    flex: none;
    padding: 32px 0;
  }
  .login-box {
    width: 95vw;
    min-width: 0;
    padding: 18px 6px 18px 6px;
  }
}
::-webkit-scrollbar {
  width: 0 !important;
  height: 0 !important;
  display: none;
}
#footer{
  margin-top: 0%;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background: #fff;
}
.dialog-footer {
  /* 居中 */
  margin-top: -20px;
}
</style> 